package com.bird.thread.base.stopthread.volatiledemo;

/**
 * @author sijunqiang
 * @data 2021/6/26 17:40
 * @description: volatile 演示用volatile 终止线程的。
 * 这种的方式不正确
 */
public class WrongWayVolatile implements Runnable {


    // volatile：修饰的属性-具有可见性。就是说 多个线程都可以看到canceled的真实的值。
    private volatile boolean canceled = false;


    @Override
    public void run() {
        int num = 0;
        try {
            while (num <= 10000 && !canceled) {
                if (num % 100 == 0) {
                    System.out.println(num + "是100的倍数");
                }
                num++;
                Thread.sleep(1);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        WrongWayVolatile r = new WrongWayVolatile();
        Thread thread = new Thread(r);
        thread.start();
        Thread.sleep(5000);
        // 这里采用 canceled的方式 停止线程
        r.canceled = true;
    }
}
